package com.ruoyi.quartz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.AddGroup;
import com.ruoyi.system.domain.Member;
import com.ruoyi.system.domain.Plaza;
import com.ruoyi.system.enumutil.AddGroupEnum;
import com.ruoyi.system.enumutil.PlazaEnum;
import com.ruoyi.system.service.AddGroupService;
import com.ruoyi.system.service.MemberService;
import com.ruoyi.system.service.PlazaService;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import com.ruoyi.system.mapper.SysUserMapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/*
 *  @author 雨安
 *  类名： UserInfoController
 *  创建时间：2025/2/15
 */
@RestController
@RequestMapping("/user/info")
public class UserInfoController {

    //用户表
    @Resource
    private SysUserMapper sysUserMapper;

    //会员表
    @Resource
    private MemberService memberService;

    //群聊
    @Resource
    private AddGroupService addGroupService;

    //广场
    @Resource
    private PlazaService plazaService;

    //获取token
    public static String getAccessToken() throws Exception {
        String urlString = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbd664677f8367061&secret=b498ec52efbacda9913b7e717371a7fc";
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        // 读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        // 打印返回的完整响应
//        System.out.println("Response: " + response.toString());
        // 解析 JSON，提取 access_token
        JSONObject jsonResponse = new JSONObject(response.toString());
        String accessToken = jsonResponse.getString("access_token");
        // 返回 access_token
        return accessToken;
    }



    //文字判断
    private static String sendMsgSecurityCheckRequest(String accessToken, String content) {
        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken;

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头（如果需要的话，这里可以添加更多的请求头）
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");

        System.out.println(content);
        // 创建请求体
        String jsonRequest = "{\"content\":\"" + content + "\"}";
        StringEntity entity = new StringEntity(jsonRequest, "UTF-8");
        httpPost.setEntity(entity);

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");

            System.out.println(responseBody + "我的拦截结果");
            return responseBody;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //发布广场
    @PostMapping("/insert/plaza")
    public AjaxResult insertPlaza(@RequestBody Plaza plaza) throws Exception {
        //判断内容
        if (StringUtils.isBlank(plaza.getContent())){
            //返回结果
            return AjaxResult.error("请输入发布内容。");
        }
        //判断图片
        if (StringUtils.isBlank(plaza.getPlazaImg())){
            //返回结果
            return AjaxResult.error("请上传发布图片。");
        }
        /********************微信审核****************************************/
        String accessToken = getAccessToken(); // 替换为你的 access_token
        //获取响应
        String responseStr = sendMsgSecurityCheckRequest(accessToken, plaza.getContent());
        //解析数据
        JsonObject jsonResponse = JsonParser.parseString(responseStr).getAsJsonObject();
        //获取响应码
        int errcode = jsonResponse.get("errcode").getAsInt();
        //判断响应码
        if (errcode == 87014){
            //返回结果
            return AjaxResult.error("发布的内容不合法。");
        }
        /*******************微信审核******************************************/
        //查询用户
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        //判断用户不为 null
        if (Objects.nonNull(sysUser) && Objects.nonNull(sysUser.getMemberEndTime())&& sysUser.getMemberEndTime().after(new Date())){
            //设置热度
            plaza.setHeat(0);
            //设置状态
            plaza.setStatus(PlazaEnum.DaiShenHe.getStatus());
            //设置默认值
            plaza.setUserId(SecurityUtils.getUserId());
            plaza.setCreateBy(SecurityUtils.getUsername());
            plaza.setCreateTime(new Date());
            plaza.setUpdateBy(SecurityUtils.getUsername());
            plaza.setUpdateTime(new Date());
            plaza.setDeleteFlag(Boolean.FALSE);
            //执行添加
            plazaService.save(plaza);
            //返回结果
            return AjaxResult.success("发布成功");
        }else{
            //返回结果
            return AjaxResult.success("您还不是本平台高级会员,请开通会员后使用该功能。");
        }
    }

//    //置顶微信群
//    @PostMapping("/top/group/{id}")
//    public AjaxResult topGroup(@PathVariable(value = "id")Long id){
//        //查询登录用户
//        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
//        //相减判断用户是否余额足够
//        BigDecimal subtract = sysUser.getScore().subtract(BigDecimal.valueOf(5L));
//        //判断是否足够
//        if (subtract.compareTo(BigDecimal.ZERO) < 0) {
//            //返回结果
//            return AjaxResult.success("用户余额不足,请充值积分。");
//        }
//        //扣除用户余额
//        sysUser.setScore(subtract);
//        //设置默认值
//        sysUser.setUpdateBy(SecurityUtils.getUsername());
//        sysUser.setUpdateTime(new Date());
//        //执行修改
//        sysUserMapper.updateUser(sysUser);
//
//
//        //查询group
//        AddGroup addGroup = addGroupService.getOne(new LambdaQueryWrapper<AddGroup>()
//                //主键
//                .eq(AddGroup::getId,id)
//                //状态
//                .eq(AddGroup::getStatus, AddGroupEnum.ShenHeTongGuo.getStatus())
//                //逻辑删除
//                .eq(AddGroup::getDeleteFlag,Boolean.FALSE)
//        );
//        //判断group不为 null
//        if (Objects.nonNull(addGroup)) {
//            if (Objects.nonNull(addGroup.getTopEndTime()) && addGroup.getTopEndTime().after(new Date())){
//                //再原基础上加一小时
//                Calendar calendar = Calendar.getInstance();
//                //设置日期为当前置顶结束时间
//                calendar.setTime(addGroup.getTopEndTime());
//                // 加一小时
//                calendar.add(Calendar.HOUR, 1);
//                //得到日期
//                Date newTopEndTime = calendar.getTime();
//                //设置结束时间
//                addGroup.setTopEndTime(newTopEndTime);
//                //执行修改
//                addGroupService.updateById(addGroup);
//            }else{
//                //置顶一小时
//                Calendar calendar = Calendar.getInstance();
//                // 当前时间
//                calendar.setTime(new Date());
//                // 加一小时
//                calendar.add(Calendar.HOUR, 1);
//                //得到置顶结束时间
//                Date newTopEndTime = calendar.getTime();
//                //设置结束时间
//                addGroup.setTopEndTime(newTopEndTime);
//                //执行修改
//                addGroupService.updateById(addGroup);
//            }
//            //返回结果
//            return AjaxResult.success("置顶成功");
//        }else{
//            //返回结果
//            return AjaxResult.success("数据异常,请联系客服。");
//        }
//    }

    //下架群聊功能
    @PostMapping("/remove/group/{id}")
    public AjaxResult removeGroup(@PathVariable(value = "id")Long id){
        //执行修改
        addGroupService.update(new UpdateWrapper<AddGroup>().lambda()
                //用户id
                .eq(AddGroup::getUserId,SecurityUtils.getUserId())
                //发布编号
                .eq(AddGroup::getId,id)
                //设置逻辑删除
                .set(AddGroup::getDeleteFlag,Boolean.TRUE)
        );
        //返回结果
        return AjaxResult.success("下架成功");
    }


    //下架广场功能
    @PostMapping("/remove/plaza/{id}")
    public AjaxResult removePlaza(@PathVariable(value = "id")Long id){
        //执行修改
        plazaService.update(new UpdateWrapper<Plaza>().lambda()
                //用户id
                .eq(Plaza::getUserId,SecurityUtils.getUserId())
                //发布编号
                .eq(Plaza::getId,id)
                //设置逻辑删除
                .set(Plaza::getDeleteFlag,Boolean.TRUE)
        );
        //返回结果
        return AjaxResult.success("下架成功");
    }

//    //用户广场置顶
//    @PostMapping("/top/plaza/{id}")
//    public AjaxResult topPlaza(@PathVariable(value = "id")Long id){
//        //查询广场
//        Plaza plaza = plazaService.getOne(new LambdaQueryWrapper<Plaza>()
//                //主键id
//                .eq(Plaza::getId,id)
//                //状态
//                .eq(Plaza::getStatus, PlazaEnum.ShenHeTongGuo.getStatus())
//                //逻辑删除
//                .eq(Plaza::getDeleteFlag,Boolean.FALSE)
//        );
//        //判断广场不为 null
//        if (Objects.nonNull(plaza)){
//            //查询登录用户
//            SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
//            //相减判断用户是否余额足够
//            BigDecimal subtract = sysUser.getScore().subtract(BigDecimal.valueOf(5L));
//            //判断是否足够
//            if (subtract.compareTo(BigDecimal.ZERO) > 0) {
//                //设置余额
//                sysUser.setScore(subtract);
//                //设置默认值
//                sysUser.setUpdateTime(new Date());
//                sysUser.setUpdateBy(SecurityUtils.getUsername());
//                //执行修改
//                sysUserMapper.updateUser(sysUser);
//                //将广场热度增加 1w
//                plaza.setHeat(plaza.getHeat() + 10000);
//                //设置默认值
//                plaza.setUpdateBy(SecurityUtils.getUsername());
//                plaza.setUpdateTime(new Date());
//                //执行修改
//                plazaService.updateById(plaza);
//                //返回结果
//                return AjaxResult.success("置顶成功");
//            }else{
//                //返回结果
//                return AjaxResult.success("用户余额不足");
//            }
//        }else{
//            //返回结果
//            return AjaxResult.success("广场异常");
//        }
//    }

    //获取用户发布的广场信息
    @PostMapping("/get/user/plaza")
    public AjaxResult getUserGroup(@RequestBody Plaza plaza){
        //创建分页对象
        Page<Plaza> page = new Page<>();
        //设置页码
        page.setCurrent(plaza.getCurrent());
        //设置行数
        page.setSize(plaza.getSize());
        //查询
        plazaService.page(page,new LambdaQueryWrapper<Plaza>()
                //用户id
                .eq(Plaza::getUserId,SecurityUtils.getUserId())
                //逻辑删除
                .eq(Plaza::getDeleteFlag,Boolean.FALSE)
                //分页
                .last(" limit " + (plaza.getCurrent() - 1) * plaza.getSize() +"," + plaza.getSize())
        );
        //设置总行数
        page.setTotal(plazaService.count(new LambdaQueryWrapper<Plaza>()
                //用户id
                .eq(Plaza::getUserId,SecurityUtils.getUserId())
                //逻辑删除
                .eq(Plaza::getDeleteFlag,Boolean.FALSE)
        ));
        //遍历数据
        page.getRecords().stream().forEach(ele->{
            //判断用户id不为 null
            if (Objects.nonNull(ele.getUserId())){
                //查询用户
                SysUser sysUser = sysUserMapper.selectUserById(ele.getUserId());
                //判断 赋值
                if (Objects.nonNull(sysUser)) {
                    //判断用户是否有会员编号
                    if (Objects.nonNull(sysUser.getMemberId()) && sysUser.getMemberEndTime().after(new Date())){
                        //设置会员名
                        sysUser.setMemberName("高级会员");
                    }else{
                        //代表没开会员
                        sysUser.setMemberName("普通会员");
                    }
                    //设置用户
                    ele.setSysUser(sysUser);
                }
            }
        });
        //返回结果
        return AjaxResult.success(page);
    }


    //获取用户发布的群聊详细
    @PostMapping("/get/user/group")
    public AjaxResult getUserGroup(@RequestBody AddGroup addGroup){
        //创建分页对象
        Page<AddGroup> page = new Page<>();
        //设置页码
        page.setCurrent(addGroup.getCurrent());
        //设置行数
        page.setSize(addGroup.getSize());
        //查询
        addGroupService.page(page,new LambdaQueryWrapper<AddGroup>()
                //用户id
                .eq(AddGroup::getUserId,SecurityUtils.getUserId())
                //逻辑删除
                .eq(AddGroup::getDeleteFlag,Boolean.FALSE)
                //排序
                .orderByDesc(AddGroup::getTopEndTime)
                //分页
                .last(" limit " + (addGroup.getCurrent() - 1) * addGroup.getSize() +"," + addGroup.getSize())
        );
        //设置总行数
        page.setTotal(addGroupService.count(new LambdaQueryWrapper<AddGroup>()
                //用户id
                .eq(AddGroup::getUserId,SecurityUtils.getUserId())
                //逻辑删除
                .eq(AddGroup::getDeleteFlag,Boolean.FALSE)
        ));
        //遍历数据
        page.getRecords().forEach(ele->{
            Date createTime = ele.getCreateTime(); // 替换为实际获取时间的方式
            if (Objects.nonNull(createTime)) {
                long currentTimeMillis = System.currentTimeMillis();
                // 将 createTime 转换为毫秒数
                long createTimeMillis = createTime.getTime(); // 直接使用 getTime() 获取毫秒数
                // 计算时间差（以分钟为单位）
                long minutes = (currentTimeMillis - createTimeMillis) / (1000 * 60);
                if (minutes > 720){
                    ele.setFrontTime("1天前");
                }else{
                    ele.setFrontTime(String.valueOf(minutes) + "分钟前");
                }

            }
        });
        //返回结果
        return AjaxResult.success(page);
    }


    //获取用户信息
    @GetMapping("/get/user")
    public AjaxResult getUser(){
        //获取用户
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        //判断用户是否有会员编号
        if (Objects.nonNull(sysUser.getMemberId()) && sysUser.getMemberEndTime().after(new Date())){
            //设置会员名
            sysUser.setMemberName("高级会员");
        }else{
            //代表没开会员
            sysUser.setMemberName("普通会员");
        }
        //返回结果
        return AjaxResult.success(sysUser);
    }

    //修改用户信息
    @PostMapping("/update/user/info")
    public AjaxResult updateUser(@RequestBody SysUser sysUser){
        System.out.println(sysUser + "我是测试查看");
        //设置默认值
        sysUser.setUpdateBy(SecurityUtils.getUsername());
        sysUser.setUpdateTime(new Date());
        //执行修改
        sysUserMapper.updateUser(sysUser);
        //返回结果
        return AjaxResult.success("修改成功");
    }


    //获取会员列表
    @GetMapping("/get/member")
    public AjaxResult getMember(){
        //返回结果
        return AjaxResult.success(memberService.list(new LambdaQueryWrapper<Member>()
                //逻辑删除为 false
                .eq(Member::getDeleteFlag,Boolean.FALSE)
        ));
    }


    //开通会员
    @PostMapping("/open/member/{id}")
    public AjaxResult userOpenMember(@PathVariable(value = "id")Long id){
        //查询开通会员对象
        Member member = memberService.getById(id);
        //查询登录用户
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        //相减判断用户是否余额足够
        BigDecimal subtract = sysUser.getScore().subtract(member.getPrice());
        //判断是否足够
        if (subtract.compareTo(BigDecimal.ZERO) > 0){
            //设置用户余额
            sysUser.setScore(subtract);
            //设置用户会员编号
            sysUser.setMemberId(id);
            //创建新的日期对象
            LocalDate newDate;
            //设置会员有效期
            if (Objects.isNull(sysUser.getMemberEndTime())){
                //获取添加时间
                newDate = LocalDate.now().plusDays(member.getDay());
                //得到转换后的时间
                String format = newDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                //设置会员有效期
                sysUser.setMemberEndTime(java.sql.Date.valueOf(format));
            }else{
                java.util.Date memberEndTime = sysUser.getMemberEndTime();
                //获取时间
                LocalDate memberEndLocalDate = memberEndTime.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDate();
                //累加
                newDate = memberEndLocalDate.plusDays(member.getDay());
                //得到转换后的时间
                String format = newDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                //设置日期
                sysUser.setMemberEndTime(java.sql.Date.valueOf(format));
            }
            //执行修改
            sysUserMapper.updateUser(sysUser);
            //返回结果
            return AjaxResult.success("开通成功");
        }else{
            return AjaxResult.error("用户积分不足,请充值。");
        }
    }


}
